Flash Article

Building a Google Search Application with Macromedia Flash MX Professional

Ian Bogost

Media Revolution

Macromedia Flash has evolved from a simple animation tool to a scriptable nonlinear authoring tool and finally a Rich Internet Application tool. With Flash MX Professional 2004, Macromedia transforms Flash into a true visual programming environment. Flash MX Pro combines the platform's familiar animation and graphical capabilities with new visual application development tools. These tools make it easy for traditional visual programmers to make the leap to Flash and enjoy its widespread installed base, cross-platform execution, and rich-media capabilities.

If you are a visual programmer working in environments like Visual Basic, Delphi, REAL basic, or PowerBuilder, you may hesitate to take advantage of the benefits of Flash because of concerns about learning a new, unfamiliar environment. To show how easily you can transfer your existing knowledge to Flash MX Professional, I explain how you can create a simple web search application that queries the Google web API using SOAP web services:

Sample Search

Requirements

To complete this tutorial, you need the following software and materials:

Macromedia Flash MX Professional 2004


Macromedia Flash Player 7


Google Web API account and license key


To examine the entire project, download the FLA source file:

Visual Programming in Macromedia Flash

As a visual programmer, you may have already tried your hand at a previous version of Flash—and been you were likely confused and overwhelmed by it. Flash has never been more inherently complex than Visual Basic 6, Visual Studio .NET, or Delphi, but it comes from a lineage of animation tools, not programming tools. This fundamental difference has made Flash an impractical tool for visual programmers. Flash MX Professional 2004 changes all that.

Before I tout the benefits of the new version, here's a quick recap of where Flash has been. Flash 1 and 2 refined and improved the animation capabilities of the product. Flash 3 added the ability to individually animate movie clips and create stand-alone EXE files—the platform's first foray out of the browser. Flash 4 and 5 contributed major improvements to its scripting capabilities (called ActionScript), including XML support. Flash MX boasted more ECMA-compliant scripting, including objects and events, pre-built UI components like buttons and sliders, and a series of impressive add-ons for multiuser applications (Macromedia Flash Communication Server) and distributed application support (Macromedia Flash Remoting MX).

Despite these improvements, Flash development still required timeline-based authoring and manual coding. Flash MX Professional adds several major changes to Flash application authoring that help visual programmers start creating their own Rich Internet Applications.

With 97 percent worldwide web browser penetration, Flash content can be viewed on almost any platform, including web, wireless, embedded devices, and—with Macromedia Central—on desktops. While platforms like Java and .NET promise code reuse for mobile development, Flash makes code truly reusable across platforms, especially on mobile devices.

Flash code is truly reusable, unlike Java code, which developers must often tweak for each platform (although the Flash Player is not available on as many mobile platforms as Java is). You can also move Flash applications among platforms without redesigning or recoding them, unlike other tools such as Visual Studio .NET mobile web forms.

Building Flash Form Screens

The biggest change in Flash MX Professional is the addition of a true visual programming environment. Prior versions of Flash provided no way to easily define application screens like a login form or a display window. Flash developers had to kludge application screens into labeled Timeline keyframes or create custom movie clips that acted like application screens. Flash form applications make it possible to create structured applications that are independent of the Timeline.

Visual programmers familiar with Visual Basic, Delphi, and other environments will immediately notice how much more approachable forms make the Flash platform. As in Visual Basic, you can create a form quickly and add UI and data components to the form by dragging them from a toolbar in the IDE. Since Flash content lives primarily within web browsers and other containers, a Flash form is really a screen within the application, not a Windows form. You can use ActionScript commands to show and hide forms in your Flash application and control objects within them.

Another major difference between Windows forms and Flash form screens is that the latter are hierarchical and inherited (see Figure 1). When you create a form within a form, the child form inherits all the elements of its parent. Hierarchical forms take a bit of getting used to for Windows forms designers but the benefit is striking.

Figure 1. Hierarchical form screens make it easy to design different screens occupying the same space on the stage.

Figure 1. Hierarchical form screens make it easy to design different screens occupying the same space on the stage.

In VB, Delphi, and other environments, creating different areas that occupy the same form can be a nuisance (see Figure 2). Typically you use a Windows frame control to house different elements, but then you may have trouble viewing them in the designer. Hierarchical forms make it easy to move between subsections of a screen without the effort.

Figure 2. In this Visual Studio .NET Windows form application, the groups of controls overlap and need to be moved around so they can be properly manipulated.

Figure 2. In this Visual Studio .NET Windows form application, the groups of controls overlap and need to be moved around so they can be properly manipulated.

Here's how you create the framework for the Flash form application:

  1. In Flash MX Professional, choose File > New and select Flash Form Application. This creates a default application with two nested form screens.
  2. Change the instance name (in the Property inspector) of form1 to frmSearch. This form will contain the main search interface.
  3. Right-click (Control-click) frmSearch and choose Insert Nested Screen. This creates a new form screen called form2 underneath frmSearch. Change the instance name of the new form screen to frmLoading.
  4. Now you can add UI components (the equivalent of VB controls) to the forms. The application form is the parent of all the other forms in the application; anything you put on that form will also appear on any of its child forms. For this application, I placed a Google graphic in the upper left corner to show how this works.
  5. Select the frmSearch form. In the Components panel, drag a Label, Button TextInput, and TextArea component onto the Stage. Arrange the components as shown in Figure 3. (Right-click and choose Free Transform to resize the components.)
  6. Using the Property inspector, give the components the following instance names—Label: lblSearchTime; Button: btnSearch; TextInput: txtQuery; and TextArea: txtResults.
Figure 3. Arranging the UI components on the form

Figure 3. Arranging the UI components on the form

Authoring Animations

You may have been intimidated at the prospect of authoring animations in Flash because the Timeline and drawing elements required a designer's skills. Besides getting such built-in Timeline effects as drop shadows in Flash MX Professional, you can animate elements in Flash forms as easily as you can animate objects in PowerPoint. You can also author your own motion graphics using movie clips and the standard Timeline. If not, the Timeline stays neatly out of the way.

Here's how you add a simple animated element to the application. For these purposes, add a "loading" element that lets the user know the search is executing:

  1. Select the frmLoading form screen.
  2. In the bottom right corner, add a graphical or text element that indicates "loading progress" to the user (see Figure 4). I added a barber pole–style progress bar that I made in a movie clip. You could just add a text tool element (that says "Loading...") and choose Modify > Timeline Effects to create an animation without any authoring at all.
  3. Hide frmLoading by selecting it and changing the visible property in the Property inspector to false. This prevents the loading widget from appearing by default. Later you'll make this screen visible with ActionScript while the search is executing.
Figure 4. The loading element on the frmLoading form. You can choose any visual element you wish.

Figure 4. The loading element on the frmLoading form. You can choose any visual element you wish.

Connecting to Data Sources with Components

Flash MX Professional sports a new component architecture, both for UI components and the new data components. In Flash, components aren't compiled code libraries like DLLs. Rather, they are equivalent to controls in VB or Delphi. Flash Professional adds XMLConnector and WebServiceConnector components to automate the interfaces with these two common data sources.

New component bindings allow you to define inputs and outputs for data components. Using the visual design panels built into the IDE, you wire XMLConnector or WebServiceConnector parameters directly to UI components in your forms. Flash features a Parameter tab on the Component inspector that works just like the property pages in VB.

Here's how you use these techniques to connect your application to the Google search service:

  1. Drag a WebServiceConnector component from the Components panel to the frmSearch form screen. It doesn't matter where you put it; the component won't be visible in the published application. Give the component an instance name of GoogleSearch.
  2. Select the GoogleSearch component and open the Component inspector. This is where you establish the web service settings. Select the Parameters tab and set the WSDLURL parameter to Google's WSDL URI (as of this writing, it's http://api.google.com/GoogleSearch.wsdl). Flash automatically queries the service and retrieves its available operations. From the operations pop-up menu, select doGoogleSearch (see Figure 5).
  3. Figure 5. Selecting the web service operation in the Component inspector

    Figure 5. Selecting the web service operation in the Component inspector

  4. Select the Bindings tab in the Component inspector. This panel allows you to bind the web service inputs and outputs directly to a UI component in the application. Click the + icon to choose which parameters to bind. Input parameters are indicated by a right arrow and output parameters by a left arrow (see Figure 6). The Google interface requires all these input parameters, so add those one by one to the bindings list. Because you're also binding one output parameter, results.searchTime, add it to the list.
  5. Figure 6. Selecting web service parameters in the Component inspector

    Figure 6. Selecting web service parameters in the Component inspector

  6. For each binding in the list, you need to set a UI component, a variable reference, or a literal value to pass to or from the web service. First select params.q from the binding list—the search query string to pass to the Google service. To bind it to the TextInput component on the frmSearch form, click the "find" icon in the Bound To row. Flash opens the Bound To dialog box, which displays a hierarchical list of components in your application. Find the txtQuery component instance, select it, and click OK (shown in Figure 7).
  7. Figure 7. Binding the web service input parameter to a UI component in the Component inspector

    Figure 7. Binding the web service input parameter to a UI component in the Component inspector

  8. Fill in the rest of the input parameters for the Google service. The other parameters can take literal inputs. To define a literal input, follow the same procedure as in Step 4, except in the Bound To dialog check Use Constant Value and enter the literal into the corresponding text box. Listing 1 shows what values to use for each input parameter.
  9. params.key		[Your Google Web API License Key]
    params.start 		0
    params.maxResults		10
    params.filter		true
    params.restrict		[empty string]
    params.safeSearch		true
    params.lr			[empty string]
    params.ie			[empty string]
    params.oe			[empty string]
    

    Listing 1. doGoogleSearch web service parameter settings

  10. Repeat Step 4 for the results.searchTime output parameter, binding it to the lblSearchTime component instance on frmSearch. The component system allows you to format the input or output before binding. Since the searchTime parameter is just a floating-point number, format this value to make it more intelligible to users. From the Formatter pop-up menu, select Compose String. Then click Formatter Options, and enter the following string into the dialog box:

    Search time: <.> seconds

    The parameter value will be substituted for the <.> placeholder when the component binds.

Note: Flash security sandbox settings currently do not allow direct access to a remote web service without a proxy class when the Flash application runs inside a website. To learn more about proxy classes and the Flash security sandbox, see "Tunneling Macromedia Flash Communications Through Firewalls and Proxy Servers" and "Exploring the Technical Changes to Macromedia Flash Communication Server MX 1.5." However, this will work on your computer if you have Flash or Flash Professional installed because of the special developer version of Flash Player you get. This example won't work without the server-side proxy.

Attaching Script Actions

Macromedia Flash MX 2004 features a new version of the application's native scripting language. ActionScript 2 is object-oriented and complies with ECMA-262 Edition 4. Still, visual programmers need to become familiar with the unique way that Flash attaches script actions to events in the application.

New behaviors make the process of triggering scripted UI component events much easier than in previous versions of Flash.

Here's how you use a behavior to trigger the web service and display its results:

  1. Click the btnSearch button on frmSearch. In the Behaviors panel, click the + icon and choose Data > Trigger Data Source. In the resulting dialog box, select GoogleSearch WebServiceConnector and click OK (see Figure 8).
  2. Figure 8. Binding a button event to the web service data source trigger in the Behaviors panel

    Figure 8. Binding a button event to the web service data source trigger in the Behaviors panel

  3. With btnSearch still selected, open the Actions panel. You'll see that Flash automatically added the code to trigger the web service when the user clicks the Search button.
  4. Any web service output you don't bind in the Component inspector needs to be managed with code. Just before the trigger event, add the code in Listing 2. These event listeners allow you to intercept the web service's send and result events and perform additional operations with ActionScript.
  5. on (click) {
    	
    	// Trigger Data Source Behavior
    	// Macromedia 2003
    	this._parent.GoogleSearch.addEventListener("send", onGoogleSearch);
    	this._parent.GoogleSearch.addEventListener("result", onGoogleSearchResult);
    	this._parent.GoogleSearch.trigger();
    
    }
    

    Listing 2. The btnSearch click event handler

  6. Add the ActionScript functions that handle these events. The code in Listing 3 does some interface work like enabling and disabling components while the search is in progress. Most importantly it iterates through the results returned from Google, formats them using HTML, and displays them in the txtResults TextArea instance. If you want to change the data or formatting, consult the Web Services panel to see the output parameter schema returned from the doGoogleSearch operation
  7. on (click) {
    	
    	var onGoogleSearch = function()
    	{
    		// Show the barber pole and disable search
    		_root.application.frmSearch.frmLoading.visible = true;
    		this._parent.txtResults.text = "";
    		this._parent.lblSearchTime.text = "";
    		this.enabled = false;
    		this._parent.txtQuery.enabled = false;
    	}
    	
    	var onGoogleSearchResult = function()
    	{
    		var res = this._parent.GoogleSearch.results.resultElements; // shorthand
    		for (var i = 0; i < res.length; i++) 
    		{
    			var s = "";
    			s += "<a href=\"" + res[i].URL + "\"><font size=\"+1\" color=\"#0000FF\"><u>" + res[i].title + "</u></font>>lt;/a><br>";
    			s += res[i].snippet + "<br>";
    			if (res[i].summary != "") { s += "<font color=\"#999999\">Description: </font>" + res[i].summary + "<br>"; }
    			s += "<a href=\"" + res[i].URL + "\"><font color=\"#009900\"><u>" + res[i].URL + "</u></font></a> - " + res[i].cachedSize;
    			s += "<br><br>";
    			this._parent.txtResults.text += s;
    		}
    
    		// Hide the barber pole and reenable the search
    		_root.application.frmSearch.frmLoading.visible = false;
    		this.enabled = true;
    		this._parent.txtQuery.enabled = true;
    	}
    	
    	// Trigger Data Source Behavior
    	// Macromedia 2003
    	this._parent.GoogleSearch.addEventListener("send", onGoogleSearch);
    	this._parent.GoogleSearch.addEventListener("result", onGoogleSearchResult);
    	this._parent.GoogleSearch.trigger();
    
    }
    

    Listing 3. The send and result event handlers for the Google web service

You're ready to publish your application. Publishing is the equivalent of building or compiling in Visual Studio and other IDEs. Select File > Publish or just press Control-Enter to publish using the default settings.

Now try out some Google searches!

Benefits of Flash

Let's review the benefits of Flash MX Professional as a visual programming environment:

  • More like the visual programming environment you know. There's no denying that Flash has a long heritage as a design and animation tool. With Flash MX Professional visual programmers can build visual applications that can—but don't need to—take advantage of the rich media capabilities of Flash. Forms, object-oriented ECMA-262–compliant ActionScript, components, and events make Flash programming more like VB programming than ever before. With unique rich media capabilities at your fingertips, Flash offers a lot more than traditional visual programming tools.
  • Rich applications. Even if you're not a designer, you can take advantage of easy-to-use Timeline effects and behaviors to add motion graphics to your form applications. Try doing this in Visual Basic!
  • True cross-platform, cross-device compatibility. Flash content can be viewed on almost any platform, including web, wireless, embedded devices, and (with Macromedia Central) on the desktop. Flash code is more reusable than Java code. You can move Flash applications among platforms without significant redesigning or recoding. For instance, converting the Google search application so it works on mobile devices or handhelds that support Flash Player 7 requires nothing more than resizing or rearranging the components on the Stage to fit a smaller screen size.

Macromedia Flash MX Professional is not a replacement for a Windows application IDE like Delphi or Visual Studio. However, visual programmers who want to author rich applications for deployment online, on handhelds, or on devices will discover familiar scenery in this new version of Flash.


About the author

Ian Bogost is Vice President of Technology for Media Revolution, where he leads the design and development of the company's award-winning interactive marketing solutions, and manages marketing campaigns and technology initiatives for numerous Fortune 1000 companies. Before joining Media Revolution, Ian worked as a developer and artist at a host of interactive publishing and advertising agencies, including Digital Evolution/US Interactive, Rubin Postaer Interactive, and Team One/Saatchi Saatchi Advertising. He has also worked with US Sailing and various United States Congressional candidates. Ian is an established industry pioneer and frequently lectures on interactive production, narrative, and theory. His articles and reviews on web development and Rich Media Application integration have appeared in numerous industry publications.